<template>
	<view class="salle-container">

		<!-- 内容区域 -->
		<view class="content-box">
			<scroll-view scroll-y class="scroll-box" @scrolltolower="nextPage" refresher-enabled
				:refresher-triggered="isRefreshing" @refresherrefresh="onRefresh" refresher-background="#f5f5f5">
				<view class="salle-list">
					<view class="task-item" v-for="(item, index) in taskList" :key="index"
						@click="showTaskDetail(item)">
						<view class="task-logo">
							<image :src="item.titleImg"></image>
						</view>
						<view class="task-info">
							<view class="task-title">{{ item.title }}</view>
							<view class="task-desc">{{ item.describeText }}</view>
							<view class="task-amount">¥{{ item.goodsPrice }}</view>
						</view>
					</view>
					<u-loadmore v-if="taskList.length > 0" :status="status" />
					<empty title="暂无任务" :isShow='false' v-if="taskList.length == 0"></empty>
				</view>
			</scroll-view>
		</view>


 <view class="float-btn" @click="goToMyOrders">
        
			<image src='/static/images/index/order.png'></image>
        </view>
		
	

		<!-- 任务详情弹窗 -->
		<u-popup v-model="showDetail" mode="bottom" height="80%" border-radius="16" style="z-index: 100;">
			<view class="task-detail" v-if="currentTask">
				<view class="detail-header">
					<u-image :src="currentTask.img" width="60px" height="60px" radius="4"></u-image>
					<view class="header-info">
						<view class="detail-title">{{ currentTask.title }}</view>
						<view class="detail-amount">¥{{ currentTask.goodsPrice }}</view>
					</view>
				</view>

				<view class="detail-content">
					<view class="content-item">
						<view class="item-label">推广内容</view>
						<view class="item-value">{{ currentTask.describeText }}</view>
					</view>
					<view class="content-item">
						<view class="item-label">曝光量</view>
						<view class="item-value">{{ currentTask.exposureNum }}</view>
					</view>
					<view class="content-item">
						<view class="item-label">任务详情</view>
						<view class="item-value">
							<u-image :src="currentTask.titleImg" width="100%" height="380px" radius="4"
								@click="previewImage(currentTask.titleImg)"></u-image>
						</view>
					</view>
					<view class="content-item" style="margin-bottom: 100px;">
						<view class="item-label">推广者信息</view>
						<view class="spreader-info">
							<!-- <u-image :src="currentTask.spreaderImg" width="60px" height="60px" radius="4"></u-image> -->
							<view>推广者：{{ currentTask.spreaderName }}</view>
							<view>简介：{{ currentTask.spreaderDescribe }}</view>
							<view>联系方式：{{ currentTask.spreaderPhone }}</view>
							<view>综合粉丝数：{{ currentTask.spreaderFans }}</view>
						</view>
					</view>
				</view>

				<view class="detail-footer">
					<u-button type="primary" @click="handleOrder">立刻下单</u-button>
				</view>
			</view>
		</u-popup>

		<!-- 添加支付弹窗 -->
		<u-popup v-model="showPay" mode="bottom" border-radius="14" :closeable="true">
			<view
				style="width: 100%;text-align: center;font-size:38rpx;font-weight: bold;margin-top:15rpx;margin-bottom: 80rpx;">
				选择支付方式
			</view>
			<view @click="goMoney" class="flex align-center justify-end" style="margin-right: 20rpx;color: #8B8FF0;">
				<view class="" style="color: #666666;">
					金豆不足？
				</view>
				去充值
			</view>
			<view style="display: flex;height: 100upx;align-items: center;padding: 20upx 30rpx;"
				v-for="(item, index) in openLists" :key='index' @tap='selectWay(item.id)'>
				<view style="display: flex;width:80%;align-items: center;">
					<image :src="item.image" style="width: 55upx;height: 55upx;"></image>
					<view style="font-size: 30upx;margin-left: 20upx;width: 70%;">{{ item.text }}</view>
				</view>
				<view style="width: 20%;display: flex;justify-content: flex-end;">
					<radio-group name="openWay" style="margin-left: 20upx;">
						<label class="tui-radio">
							<radio color="#8B8FF0" style="transform:scale(0.7)"
								:checked="openWay === item.id ? true : false" />
						</label>
					</radio-group>
				</view>
			</view>
			<view class="confirm-pay-btn" @tap="pay()">确认支付</view>
		</u-popup>
	</view>
</template>

<script>
import empty from '@/components/empty.vue'
export default {
	components: {
		empty
	},
	name: 'SalleList',
	data() {
		return {
			loadStatus: 'loadmore',
			page: 1,
			pageSize: 10,
			taskList: [],
			showDetail: false,
			currentTask: null,
			isRefreshing: false,
			allTestData: [],
			showPay: false,
			openWay: 0,
			openLists: [],
		}
	},
	onLoad() {
		this.getList()
		this.initPayMethod()
	},
	onShow() {
		this.getList()
	},
	methods: {
		// 新增跳转到我的订单页面方法
		goToMyOrders() {
			this.$navTo('/me/spreader/ordersUser/index')
		},
		getList() {
			this.$u.get("/app/spreader/getProductInfoPage", {
				page: this.page,
				limit: this.pageSize
			}).then(
				res => {
					if (res.code === 0) {
						this.pages = res.data.pages
						if (this.page < this.pages) {
							this.status = 'loadmore'
						} else {
							this.status = 'nomore'
						}
						if (this.page === 1) {
							this.taskList = res.data.records
						} else {
							this.taskList = [...this.taskList, ...res.data.records]
						}
					} else {
						uni.stopPullDownRefresh();
					}
				});
		},
		showTaskDetail(task) {
			this.$navTo('/me/spreader/salleList/info?id='+task.id)
			// this.currentTask = task
			// this.showDetail = true
		},

		handleOrder() {
			this.showPay = true
		},
		// 添加返回方法
		goBack() {
			uni.navigateBack()
		},
		nextPage() {
			if (this.page < this.pages) {
				this.page += 1
				this.status = 'loading'
				this.getList()

			} else {
				this.status = 'nomore'
			}
		},
		onReachBottom: function () {
			console.log('onReachBottom>>>>>>>')
			if (this.page < this.pages) {
				this.page += 1
				this.status = 'loading'
				this.getList()

			} else {
				this.status = 'nomore'
			}

		},
		// 新增：下拉刷新方法
		async onRefresh() {
			if (this.isRefreshing) return

			this.isRefreshing = true

			// 重置页码和加载状态
			this.page = 1
			this.loadStatus = 'loadmore'

			// 模拟刷新延迟
			await new Promise(resolve => setTimeout(resolve, 1000))

			// 重新加载第一页数据
			await this.getList()

			// 结束刷新状态
			this.isRefreshing = false
			uni.showToast({
				title: '刷新成功',
				icon: 'success'
			})

			// 实际接口调用可以参考上面 onLoad 方法中注释的代码
		},
		// 添加图片预览方法
		previewImage(url) {
			uni.previewImage({
				urls: [url],
				current: url,
				indicator: 'number',
				loop: false
			});
		},
		// 初始化支付方式
		initPayMethod() {
			// #ifdef APP
			if (plus.os.name.toLowerCase() === 'android') {
				this.openLists = [{
					image: '/static/images/pay/zhifubao.png',
					text: '支付宝',
					id: 2
				}, {
					image: '/static/images/pay/lingqian.png',
					text: '金豆支付',
					id: 3
				}]
				this.openWay = 2
			} else {
				let checkIosPay = this.$queue.getData('checkIosPay')
				if (checkIosPay === '是') {
					this.openLists = [{
						image: '/static/images/pay/lingqian.png',
						text: '金豆支付',
						id: 3
					}]
					this.openWay = 3
				} else {
					this.openLists = [{
						image: '/static/images/pay/zhifubao.png',
						text: '支付宝',
						id: 2
					}, {
						image: '/static/images/pay/lingqian.png',
						text: '金豆支付',
						id: 3
					}]
					this.openWay = 1
				}
			}
			// #endif

			// #ifdef MP-WEIXIN
			this.openLists = [{
				image: '/static/images/pay/lingqian.png',
				text: '金豆支付',
				id: 3
			}]
			this.openWay = 3
			// #endif

			// #ifdef H5
			let ua = navigator.userAgent.toLowerCase()
			if (ua.indexOf('micromessenger') !== -1) {
				this.openLists = [{
					image: '/static/images/pay/weixin.png',
					text: '微信',
					id: 1
				}, {
					image: '/static/images/pay/lingqian.png',
					text: '金豆支付',
					id: 3
				}]
				this.openWay = 1
			} else {
				this.openLists = [{
					image: '/static/images/pay/zhifubao.png',
					text: '支付宝',
					id: 2
				}, {
					image: '/static/images/pay/lingqian.png',
					text: '金豆支付',
					id: 3
				}]
				this.openWay = 2
			}
			// #endif
		},

		// 选择支付方式
		selectWay(id) {
			this.openWay = id
		},

		// 去充值
		goMoney() {
			uni.navigateTo({
				url: '/me/wallet/wallet'
			})
		},
		pay() {
			console.log(this.openWay)
			let that = this
			if (that.openWay == 4) { //抖音支付
				that.toutiaoPay()
			} else if (that.openWay == 5) { //快手支付

			} else {

				let data = {
					productId: that.currentTask.id
				}
				let userId = uni.getStorageSync('userId')
				// that.$u.api.insertSpreaderOrders(data).then(res => {
				that.$Request.getT('/app/order/insertSpreaderOrders', data).then(res => {
					if (res.code == 0) {
						if (that.openWay == 1) {
							// #ifdef MP-WEIXIN
							that.$u.post('app/wxPay/wxPayJsApiOrder?orderId=' + res.data.ordersId).then(
								ret => {
									uni.requestPayment({
										provider: 'wxpay',
										timeStamp: ret.data.timestamp,
										nonceStr: ret.data.noncestr,
										package: ret.data.package,
										signType: ret.data.signType,
										paySign: ret.data.sign,
										success: function (suc) {
											console.log('success:' + JSON.stringify(suc));
											that.showPay = false
											uni.showToast({
												title: '支付成功',
												icon: 'success'
											})

											let data = {
												userId: uni.getStorageSync('userId')
											}
											that.$u.api.userVip(data).then(res => {
												if (res.code == 0 && res.data && res
													.data
													.isVip ==
													2) {
													uni.setStorageSync('isVIP', true)
												} else {
													uni.setStorageSync('isVIP', false)
												}
											})
											setTimeout(d => {
												let data = {
													flag: true
												}
												uni.$emit('back', data)
												uni.navigateBack(1)
											}, 1000);
										},
										fail: function (err) {
											console.log('fail:' + JSON.stringify(err));
											uni.showToast({
												title: '支付失败',
												icon: 'none'
											})
										}
									});
								});
							// #endif
							// #ifdef H5
							let ua = navigator.userAgent.toLowerCase();
							if (ua.indexOf('micromessenger') !== -1) {

								this.$u.post('/app/MiHuaPay/pay?orderId=' + res.data.ordersId +
									'&classify=1&payType=H5_WEIXIN').then(red => {
										if (red.code === 0) {
											/* this.callPay(red.data); */
											window.location.href = red.data
										} else {
											uni.showToast({
												icon: 'none',
												title: '支付失败!'
											});
										}

									});
							}
							// #endif
							// #ifdef APP
							this.$u.post("/app/wxPay/payAppOrder?orderId=" + res.data.ordersId).then(red => {
								if (red.code == 0) {
									that.setPayment('wxpay', JSON.stringify(red
										.data));
								} else {
									uni.showToast({
										title: red.msg,
										icon: 'none'
									})
								}
							});
							// #endif
						} else if (that.openWay == 2) {
							// #ifdef H5
							this.$u.post('/app/aliPay/payOrderSp?orderId=' + res.data.ordersId +
								'&classify=2&payType=ALIPAY_H5').then(
									red => {
										if (red.code === 0) {
											const div = document.createElement('div')
											div.innerHTML = red.data //此处form就是后台返回接收到的数据
											document.body.appendChild(div)
											document.forms[0].submit()
										} else {
											uni.showToast({
												icon: 'none',
												title: '支付失败!'
											});
										}
									});
							// #endif
							// #ifdef APP
							this.$u.post('/app/aliPay/payOrderSp?orderId=' + res.data.ordersId +
								'&classify=1&payType=ALIPAY_APP').then(
									red => {
										if (red.code === 0) {
											that.setPayment('alipay', red.data);
										} else {
											uni.showToast({
												icon: 'none',
												title: '支付失败!'
											});
										}
									});
							// #endif
						} else if (that.openWay == 3) {
							that.$queue.showLoading('支付中...')
							that.$Request.postT("/app/order/payOrders", {
								orderId: res.data.ordersId,
							}).then(red => {
								uni.hideLoading();
								if (red.code == 0) {
									that.showPay = false
									uni.showToast({
										title: '支付成功',
										icon: 'success'
									})

									let data = {
										userId: uni.getStorageSync('userId')
									}
									that.$u.api.userVip(data).then(res => {
										if (res.code == 0 && res.data && res.data
											.isVip ==
											2) {
											uni.setStorageSync('isVIP', true)
										} else {
											uni.setStorageSync('isVIP', false)
										}
									})
									setTimeout(d => {
										let data = {
											flag: true
										}
										uni.$emit('back', data)
										uni.navigateBack(1)
									}, 1000);
								} else {
									that.$queue.showToast(red.msg)
								}
							});
						}

					} else {
						uni.showToast({
							title: res.msg,
							icon: "none"
						})
					}
				})
			}

		},
		isCheckPay(code, name, order) {
			if (code == 0) {
				console.log('999999999999')
				this.setPayment(name, order);
			} else {
				uni.hideLoading();
				uni.showToast({
					title: '支付信息有误'
				});
			}
		},
		setPayment(name, order) {
			let that = this
			uni.requestPayment({
				provider: name,
				orderInfo: order, //微信、支付宝订单数据
				success: function (res) {
					uni.hideLoading();
					that.showPay = false
					uni.showToast({
						title: '支付成功',
						icon: 'success'
					})

					let data = {
						userId: uni.getStorageSync('userId')
					}
					that.$u.api.userVip(data).then(res => {
						if (res.code == 0 && res.data && res.data
							.isVip ==
							2) {
							uni.setStorageSync('isVIP', true)
						} else {
							uni.setStorageSync('isVIP', false)
						}
					})
					setTimeout(d => {
						let data = {
							flag: true
						}
						uni.$emit('back', data)
						uni.navigateBack(1)
					}, 1000);
				},
				fail: function (err) {
					uni.hideLoading();
				},
				complete() {
					uni.hideLoading();
				}
			});
		},
		callPay: function (response) {
			if (typeof WeixinJSBridge === "undefined") {
				if (document.addEventListener) {
					document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(response), false);
				} else if (document.attachEvent) {
					document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(response));
					document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(response));
				}
			} else {
				this.onBridgeReady(response);
			}
		},
	}
}
</script>

<style>
/* 添加全局样式，不使用 scoped */
/* 预览图片容器 */
.uni-popup {
	z-index: 100 !important;
}

.uni-preview-image {
	z-index: 999999 !important;
}

.uni-preview-image-mask {
	z-index: 999998 !important;
}

/* 图片预览的根节点 */
uni-image-preview {
	z-index: 999999 !important;
}

/* 预览时的遮罩层 */
.uni-transition {
	z-index: 999999 !important;
}
</style>

<style lang="scss" scoped>
	page{
		background-color: #F7F8FF;
	}
.salle-container {
	display: flex;
	flex-direction: column;
	// height: 100vh;
	// background: #f5f5f5;
}

.content-box {
	flex: 1;
	// margin-top: 35px; // 只需要考虑导航栏高度
	height: calc(100vh - 35px);
}

.scroll-box {
	height: 100%;
}

.salle-list {
	padding: 20rpx 30rpx;
}


.task-logo {
	width: 140rpx;
	height: 140rpx;
	background: #F7F7F7;
	border-radius: 10rpx;
	margin-right: 16px;
	display: flex;
	align-items: center;
	justify-content: center;
	image{
		width: 117rpx;
		height: 114rpx;
	}
}
	

.task-item {
	display: flex;
	padding: 30rpx 20rpx;
	background: #fff;
	border-radius: 10px;
	margin-bottom: 20px;



	.task-info {
		flex: 1;
		position: relative;
		.task-title {
			font-weight: bold;
			font-size: 28rpx;
			color: #1A1A1A;
		}

		.task-desc {
			font-weight: 500;
			font-size: 24rpx;
			color: #999999;
			padding-top: 10rpx;
		}

		.task-amount {
			font-weight: bold;
			font-size: 24rpx;
			color: #FD7885;
			position: absolute;
			right: 0;
			bottom: 0;
		}
	}
}

.task-detail {
	padding: 20px;

	.detail-header {
		display: flex;
		align-items: center;
		margin-bottom: 20px;

		.header-info {
			margin-left: 12px;

			.detail-title {
				font-size: 18px;
				font-weight: bold;
				margin-bottom: 8px;
			}

			.detail-amount {
				font-size: 20px;
				color: #f44;
				font-weight: bold;
			}
		}
	}

	.detail-content {
		.content-item {
			margin-bottom: 16px;

			.item-label {
				font-size: 16px;
				font-weight: bold;
				margin-bottom: 8px;
			}

			.item-value {
				font-size: 14px;
				color: #666;
				line-height: 1.5;
			}

			.spreader-info {
				font-size: 14px;
				color: #666;
				line-height: 1.8;
			}
		}
	}

	.detail-footer {
		position: fixed;
		bottom: 20px;
		left: 20px;
		right: 20px;
	}
}

// 新增悬浮按钮样式
.float-btn {
    position: fixed;
    right: 30rpx;
   
    z-index: 99;
	
	bottom: 100rpx;
	image{
		width: 100rpx;
		height: 100rpx;
	}
	}


// 添加支付相关样式
.confirm-pay-btn {
	width: 690rpx;
	height: 80rpx;
	background: #8B8FF0;
	color: #FFFFFF;
	text-align: center;
	line-height: 80rpx;
	border-radius: 50rpx;
	margin: 30rpx;
}
</style>